Logical Operators will allow us to combine multiple comparison operators. The logical operators we will learn about are:
The best way to explain these is to see some examples.
# Imagine the variable x
x <- 10
Now we want to know if 10 is less than 20 AND greater than 5:
x < 20
x > 5
x < 20 & x > 5
We can also add parenthesis for readability and to make sure the order of comparisons is what we expect:
(x < 20) & (x>5)
(x < 20) & (x>5) & (x == 10)
We can basically think of this as a series of Logical Boolean values, TRUE & TRUE & TRUE. We return a single TRUE if they are all TRUE. Let's see an example of this not being the case:
x==2 & x > 1
Returned FALSE because while x > 1 is TRUE, we need BOTH to be TRUE, thus the AND statement &. What if we only want one of them to be true? That's when we use OR |. For example:
x==2 | x > 1
Here we only need one or the other to be true!
x==1 | x==12
You can think about NOT as reversing any logical value in front of it, basically asking, "Is this NOT true?" For example:
(10==1)
!(10==1)
# We can stack them (pretty uncommon, but possible)
!!(10==1)
Here's a quick example of a real use case for these operators. Imagine the following data frame:
df <- mtcars
df
This shows some data for various car models (its built in to R). Let's grab models with at least 20 mpg:
df[df['mpg'] >= 20,] # Notice the use of indexing with the comma
# subset(df,mpg>=20) # Could also use subset
Great! Now let's combine filters with logical operators! Let's grab rows with cars of at least 20mpg and over 100 hp.
df[(df['mpg'] >= 20) & (df['hp'] > 100),]
Hopefully you know see how useful these type of logical operators can be!
We have two options when use logical operators, a comparison of the entire vectors element by element, or just a comparison of the first elements in the vectors, to make sure the output is a single Logical, don't worry too much about this right now, we will cover it in more depth later on.
tf <- c(TRUE,FALSE)
tt <- c(TRUE,TRUE)
ft <- c(FALSE, TRUE)
tt & tf
tt | tf
To compare first elements use && or ||
ft && tt
tt && tf
tt || tf
tt || ft
Ok that's it for logical operators! This knowledge will help us when we use it for basic if and else statements!